# import openpyxl
# from openpyxl.utils import get_column_interval
#
# excel_read_path = "C:\\Users\\14197\\Desktop\\program_donqi\\data\\00015\\00015.xlsx"
# # excel_read_path = "C:\\Users\\14197\\Desktop\\program_donqi\\data\\0005\\0005.xlsx"
# wb = openpyxl.load_workbook(excel_read_path)
# # print(wb.sheetnames)
#
# # 读取excel文件第一张sheet
# ws = wb[wb.sheetnames[0]]  # worksheet
# # print(ws)
#
# # 读取sheet表格行列数
# max_row = ws.max_row  # 行
# max_column = ws.max_column  # 列
#
# # a = ws.row_dimensions[100]
# # b = ws.column_dimensions['A']
# # c = ws.column_dimensions['B']
# # d = ws.column_dimensions['E']
# # height8 = ws.row_dimensions[120].height
# # width8 = ws.column_dimensions[get_column_letter(12)].width
#
# from openpyxl.utils.units import DEFAULT_COLUMN_WIDTH, DEFAULT_ROW_HEIGHT
#
# ssss = DEFAULT_COLUMN_WIDTH
# dddd = DEFAULT_ROW_HEIGHT
#
# print("行高")
# height_list = []
# for i in range(1, max_row + 1):
#     height = ws.row_dimensions[i].height
#     # 如果为默认行高
#     if height is None:
#         height = ws.sheet_format.defaultRowHeight
#     height_list.append(float(height))
#     print(height)
# '''
# print("列宽")
# # 读取列宽
# col_list = []
# # 默认列宽
# width = ws.sheet_format.baseColWidth + 1
# for i in range(1, max_column + 1):
#     # 判断该列宽度是否与上一列宽度相等,相等则取前一列的列宽，否则进行读取
#     if ws.column_dimensions[get_column_letter(i)].max is None:
#         col_list.append(float(width))
#     else:
#         width = ws.column_dimensions[get_column_letter(i)].width
#         col_list.append(float(width))
#     print(width)
# '''
# print("列宽")
# # 创建定长空列表
# col_list = [None for i in range(max_column)]
# for i in ws.column_dimensions:
#     # 获取此列宽下的最大、小列索引
#     if i in get_column_interval(1,max_column):
#         min = ws.column_dimensions[i].min - 1
#         max = ws.column_dimensions[i].max
#         col_list[min:max] = [ws.column_dimensions[i].width] * (max - min)
# # 为剩余列赋默认列宽
# # for i in range(len(col_list)):
# #     if col_list[i] is None:
# #         col_list[i] = ws.sheet_format.baseColWidth + 1
# print(col_list)
#
# '''
# # b = list(ws.columns)[2]
# # b = ws.column_dimensions["A:594948B"]
# for i in ws.column_dimensions:
# 	print(i, ws.column_dimensions[i].width)
# '''
#
# if 'B' < 'AQ':
#     print(1)
# else:
#     print(0)
#
# # ws.row_dimensions[1].height = 10
# # ws.column_dimensions[get_column_letter(1)].width = 10
# # wb.save(excel_read_path)
# # vvvv2 = ws.sheet_format.baseColWidth#可
# # vvvv1 = ws.sheet_format.defaultColWidth
# # vvvv3 = ws.sheet_format.defaultRowHeight#可
# interval= get_column_interval(1,5)
#
#


# import openpyxl
# from shibie import xxx
# excel_path = "C:/Users/14197/Desktop/program_donqi/data/0007/00077.xlsx"
# wb = openpyxl.load_workbook(excel_path)
# ws = wb.worksheets[0]
#
# # print(xxx)
# # ws.cell('A4').style.alignment.wrap_text = True
# # ws.cell('A4').value = "Line 1\nLine 2\nLine 3"
# from openpyxl.styles import Alignment
#
# ws['A4'].alignment = Alignment(wrapText=True,horizontal='center', vertical='center')
# # ws['A4'] = "Line 1\nLine 2\nLine 3\nLine 3"
#
# zzz = 'AT41\n\f'
# zzz = zzz[:-2]
# ws['A4'] = zzz
# ws['A5'] = 'ascnsiv'
#
# wb.save("C:/Users/14197/Desktop/program_donqi/data/0007/000777.xlsx")
#
# print(ws['A4'].value)


# import re
# def clean_space(text):
#     """"
#     处理多余的空格
#     """
#     match_regex = re.compile(u'[\u4e00-\u9fa5。\.,，:：《》、\(\)（）]{1} +(?<![a-zA-Z])|\d+ +| +\d+|[a-z A-Z]+')
#     should_replace_list = match_regex.findall(text)
#     order_replace_list = sorted(should_replace_list,key=lambda i:len(i),reverse=True)
#     for i in order_replace_list:
#         if i == u' ':
#             continue
#         new_i = i.strip()
#         text = text.replace(i,new_i)
#     return text
#
# inp = '我今  天 赚了 10 个亿，老百姓very happy 75℃。'
# output = clean_space(inp)
# print(inp)
#
# print(output)


# import paddlehub as hub
# import cv2
#
# img = cv2.imread('C:\\Users\\14197\\Desktop\\program_donqi\\data\\0007\\orgin_cells\\A3.jpg')
# h, w = img.shape[:2]
# img = img[int(h / 20):-int(h / 20), int(w / 20):-int(w / 20)]
#
# ocr = hub.Module(name="chinese_ocr_db_crnn_server")
# # ocr = hub.Module(name="chinese_ocr_db_crnn_mobile")
# result = ocr.recognize_text(images=[img],box_thresh=0.1, text_thresh=0.1)
# print(result)


# from paddleocr import PaddleOCR, draw_ocr
# # 模型路径下必须含有model和params文件
# ocr = PaddleOCR(use_angle_cls=True,
#                 use_gpu=False)  # det_model_dir='{your_det_model_dir}', rec_model_dir='{your_rec_model_dir}', rec_char_dict_path='{your_rec_char_dict_path}', cls_model_dir='{your_cls_model_dir}', use_angle_cls=True
# # img_path = 'C:\\Users\\14197\\Desktop\\program_donqi\\data\\0007\\0007_jiaozheng.jpg'
# img_path = 'C:\\Users\\14197\\Desktop\\program_donqi\\data\\0007\\orgin_cells\\A4.jpg'
#
# result = ocr.ocr(img_path, det=False)
# for line in result:
#     print(line)

# tesseract C:\Users\14197\Desktop\program_donqi\data\0007\orgin_cells\B5.jpg reuwang -l chi_sim


# """
# text2image --text="C:\Users\14197\Desktop\font2\data.txt" --outputbase="C:\Users\14197\Desktop\font2\1.font.exp0" --fontconfig_tmpdir="%temp%" --font="simsun" --fonts_dir="C:\Users\14197\Desktop\font2\font" --xsize 1000 --ysize 1200 --margin 50  --ptsize 10
#
# tesseract num_my.font.exp0.tif num_my.font.exp0 -l font4 --psm 6 lstm.train
#
# combine_tessdata -e font4.traineddata font4.lstm
#
# lstmtraining --model_output="C:\Users\14197\Desktop\test\output\lstm_output" --continue_from="C:\Users\14197\Desktop\test\font4.lstm" --train_listfile="C:\Users\14197\Desktop\test\font4.training_files.txt" --traineddata="C:\Users\14197\Desktop\test\font4.traineddata" --debug_interval -1 --max_iterations 5000 --target_error_rate 0.05
#
# lstmtraining --stop_training --continue_from="C:\Users\14197\Desktop\test\output\lstm_output_checkpoint" --traineddata="C:\Users\14197\Desktop\test\font4.traineddata" --model_output="C:\Users\14197\Desktop\test\fnum_my2.traineddata"
#
# """


# C:/Users/14197/AppData/Local/Programs/Python/Python36/python.exe tools/infer/predict_system.py --image_dir="C:/Users/14197/Desktop/program_donqi/data/0007/orgin_cells/K4.jpg" --det_model_dir="C:/Users/14197/AppData/Local/Programs/Python/Python36/Lib/site-packages/paddleocr/inference/ch_ppocr_mobile_v2.0_det_infer/"  --rec_model_dir="C:/Users/14197/AppData/Local/Programs/Python/Python36/Lib/site-packages/paddleocr/inference/ch_ppocr_mobile_v2.0_rec_infer/" --cls_model_dir="C:/Users/14197/AppData/Local/Programs/Python/Python36/Lib/site-packages/paddleocr/inference/ch_ppocr_mobile_v2.0_cls_infer/" --use_angle_cls=True --use_space_char=True
#
# C:\Users\14197\AppData\Local\Programs\Python\Python36\python.exe tools\infer\predict_system.py --image_dir="C:\Users\14197\Desktop\program_donqi\data\0007\orgin_cells\K15.jpg" --det_model_dir="C:\Users\14197\AppData\Local\Programs\Python\Python36\Lib\site-packages\paddleocr\inference\ch_ppocr_mobile_v2.0_det_infer\"  --rec_model_dir="C:\Users\14197\AppData\Local\Programs\Python\Python36\Lib\site-packages\paddleocr\inference\ch_ppocr_mobile_v2.0_rec_infer\" --cls_model_dir="C:\Users\14197\AppData\Local\Programs\Python\Python36\Lib\site-packages\paddleocr\inference\ch_ppocr_mobile_v2.0_cls_infer\" --use_angle_cls=True --use_space_char=True
# from paddleocr import PaddleOCR
# import cv2
# resu =''
# ocr = PaddleOCR(rec_model_dir=r'C:/Users/14197/Desktop/inference/ch_ppocr_server_v2.0_rec_infer/')  # need to run only once to download and load model into memory
# # img_path = 'C:\\Users\\14197\\Desktop\\program_donqi\\data\\0007\\orgin_cells\\E6.jpg'
# img = cv2.imread('C:\\Users\\14197\\Desktop\\program_donqi\\data\\0007\\orgin_cells\\B5.jpg')
# h, w = img.shape[:2]
# img = img[int(h / 20):-int(h / 20), int(w / 20):-int(w / 20)]

# top = int(0.2 * img.shape[0])  # shape[0] = rows
# bottom = top
# left = int(0.2 * img.shape[1])  # shape[1] = cols
# right = left
# value = [0, 0, 0]
# borderType = cv2.BORDER_REPLICATE
# dst1 = cv2.copyMakeBorder(img, top, bottom, left, right, borderType, None, value)

# result = ocr.ocr(img, cls=True)
# for line in result:
#     resu +=line[1][0]+'\n'
# print(resu)


# import easyocr
# reader = easyocr.Reader(['ch_sim', 'en'],gpu = False) # need to run only once to load
# result = reader.readtext('C:\\Users\\14197\\Desktop\\program_donqi\\data\\0007\\orgin_cells\\B5.jpg')
#
# print(result)

# 显示结果
# from PIL import Image
#
# image = Image.open(img_path).convert('RGB')
# boxes = [line[0] for line in result]
# txts = [line[1][0] for line in result]
# scores = [line[1][1] for line in result]
# im_show = draw_ocr(image, boxes, txts, scores, font_path='D:/paddle_pp/PaddleOCR/doc/simfang.ttf')
# im_show = Image.fromarray(im_show)


# from paddleocr import PaddleOCR, draw_ocr
# def init():
#     ocr = PaddleOCR(use_angle_cls=True, lang="ch")  # need to run only once to download and load model into memory
#     img_path = './data/3.jpg'
#     result = ocr.ocr(img_path, cls=True)
#     for line in result:
#         print(line)
#
#
# if __name__ == "__main__":
#     init()


# import paddlehub as hub
#
# # 加载移动端预训练模型
# ocr = hub.Module(name="chinese_ocr_db_crnn_mobile")
# # 服务端可以加载大模型，效果更好
# # ocr = hub.Module(name="chinese_ocr_db_crnn_server")

import cv2
from cv2 import MORPH_RECT, MORPH_CLOSE, MORPH_OPEN


grayImg = cv2.imread(r"C:\Users\wangyu\Desktop\program_donqi\data\0007\0007.jpg", 0)
grayImg2 = grayImg
ret, _= cv2.threshold(grayImg, 0, 255, cv2.THRESH_BINARY| cv2.THRESH_OTSU)

_, thresh= cv2.threshold(grayImg, ret+45, 255, cv2.THRESH_BINARY)
grayImg = thresh

"""检测和删除垂直和水平框线"""
# 一、morphologyEx：调节形态学算子，检测水平竖直线
# 开运算保留X方向直线
kernel = cv2.getStructuringElement(MORPH_RECT, ksize=(1, 100))
grayImgy = cv2.morphologyEx(grayImg, MORPH_CLOSE, kernel)
# TODO 100应根据行高列宽二倍均值取值

# 开运算保留Y方向直线
kernel = cv2.getStructuringElement(MORPH_RECT, ksize=(100, 1))
grayImgx = cv2.morphologyEx(grayImg, MORPH_CLOSE, kernel)
# 获取框线图像
addImg = cv2.add(~grayImgy, ~grayImgx)

# 二、将框线图二值化并进行膨胀获取掩膜
# 将框线图二值化
_, thresh = cv2.threshold(addImg, 125, 255, cv2.THRESH_BINARY)
# 膨胀图像
kernel = cv2.getStructuringElement(MORPH_RECT, ksize=(5, 5))
dilated = cv2.dilate(thresh, kernel)

# 三、原图与框线图相加从而去除框线
resImg = cv2.add(grayImg, dilated)

cv2.imshow("thresh", resImg)
# cv2.imshow("resImg", resImg)
# cv2.imshow("grayImg", grayImg)
# cv2.imshow("grayImgy", grayImgy)
# cv2.imshow("grayImgx", grayImgx)
# cv2.imshow("dilated", dilated)
cv2.imshow("resImg", resImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite(r"C:\Users\wangyu\Desktop\program_donqi\data\0006\00062.jpg", grayImg2)





